package com.jml.zlhq.app.ui;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jml.zlhq.app.R;
import com.jml.zlhq.app.URLs;
import com.jml.zlhq.app.adapter.IBaseAdapter;
import com.jml.zlhq.app.adapter.MainFaXianAdapter;
import com.jml.zlhq.app.util.BaseTools;
import com.jml.zlhq.app.util.UIUtil;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class TuiJianActivity extends BaseActivity {
	private PullToRefreshListView mPullToRefreshView;
	private ListView listView;
	private IBaseAdapter adapter;
	private List<JSONObject> listItems = new ArrayList<JSONObject>();
	public static boolean freshPage;
	private Map<String,String> conditionMap;
	
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				adapter.notifyDataSetChanged();
				mPullToRefreshView.onRefreshComplete();
				if(pageEnd)mPullToRefreshView.setMode(Mode.PULL_FROM_START);
				break;
			default:
				break;
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tuijian_activity);
		
		LinearLayout leftLay = (LinearLayout) findViewById(R.id.content_header_left_lay);
		LinearLayout rightLay = (LinearLayout) findViewById(R.id.content_header_right_lay);
		leftLay.setOnClickListener(this);
		rightLay.setOnClickListener(this);
		AutoCompleteTextView centerEdit = (AutoCompleteTextView) findViewById(R.id.content_header_center_edit);
		centerEdit.setVisibility(View.GONE);
		ImageView leftImage = (ImageView) findViewById(R.id.content_header_left_img);
		leftImage.setImageResource(R.drawable.back_selector);
		ImageView roghtImage1 = (ImageView) findViewById(R.id.content_header_right_img);
		roghtImage1.setVisibility(View.INVISIBLE);
		TextView centerText = (TextView) findViewById(R.id.content_header_center_text);
		centerText.setText("推荐活动");
		TextView rightText = (TextView) findViewById(R.id.content_header_right_text);
		rightText.setVisibility(View.INVISIBLE);
		TextView centerChosed = (TextView) findViewById(R.id.content_header_center_text2);
		centerChosed.setVisibility(View.GONE);
		
		String jsonArr = getIntent().getExtras().getString("jsonArr");
		JSONArray jarr = new JSONArray();
		try {
			jarr = new JSONArray(jsonArr);
			for (int i = 0; i < jarr.length(); i++) {
				listItems.add(jarr.getJSONObject(i));
			}
		} catch (Exception e) {}
		
				
		mPullToRefreshView = (PullToRefreshListView) findViewById(R.id.tuijian_listview);
		mPullToRefreshView.setMode(Mode.DISABLED);
		mPullToRefreshView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				if(PullToRefreshBase.Mode.PULL_FROM_START == mPullToRefreshView.getCurrentMode()){
					String label = DateUtils.formatDateTime(appContext,System.currentTimeMillis(),DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);  
					mPullToRefreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
					clearData();
					loadData(null);
				}else if(PullToRefreshBase.Mode.PULL_FROM_END == mPullToRefreshView.getCurrentMode()){
					if(urlParam==null)urlParam = new HashMap<String,String>();
					pageIndex++;
					urlParam.put("pageNo", String.valueOf(pageIndex));
					loadData(urlParam);
				}
			}
		});
		listView = mPullToRefreshView.getRefreshableView();
		adapter = new MainFaXianAdapter(activity, listItems, false);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				int index = new Long(id).intValue();
				Bundle data  = new Bundle();
				data.putString("title", "活动详情");
				data.putString("id", BaseTools.getFrom("_id", listItems.get(index)));
				UIUtil.openActivity(activity, HuodongDetailActivity.class, data);
			}
		});
		
		freshPage = false;
		//loadData(null);
	}
	
	@Override
	public void onResume() {
		pageFresh = freshPage;
		super.onResume();
		freshPage = false;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==4&&resultCode==Activity.RESULT_OK&&null!=data){
			conditionMap = (Map<String,String>) data.getSerializableExtra("data");
			if(urlParam==null)urlParam = new HashMap<String,String>();
			urlParam.clear();
			urlParam.put("page", String.valueOf(0));
			urlParam.putAll(conditionMap);
			listItems.clear();
			loadData(urlParam);
		}
	}

	@Override
	public void loadData(Map<String, String> param) {
//		if(param==null){
//			param = new HashMap<String, String>();
//			param.put("pageNo", String.valueOf(pageIndex));
//		}
//		
//		HttpService.getByText(URLs.MAIN_TUIJIAN, param, new TextHttpResponseHandler() {
//			@Override
//			public void onSuccess(int arg0, Header[] arg1, String resultStr) {
//				try {
//					if(BuildConfig.DEBUG)Log.i("==result post==", resultStr);
//					JSONObject result = new JSONObject(resultStr);
//					if(result.getInt("status")==0){
//						Log.i("=====", BaseTools.getFrom("data", result));
//						JSONArray data = result.get("data").toString().equals("null")?new JSONArray():result.getJSONArray("data");
//						for (int i = 0; data!=null && i < data.length(); i++) {
//							listItems.add(data.getJSONObject(i));
//						}
//						if(data==null||data.length()<=0){
//							pageEnd = true;
//							adapter.setPageEnd(pageEnd);
//						}
//					}else{
//						if(pageIndex>0)pageIndex--;
//					}
//					mHandler.sendEmptyMessage(1);
//					
//				} catch (JSONException e) {
//					e.printStackTrace();
//				}
//			}
//			
//			@Override
//			public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
//				UIUtil.ToastMessage(activity, "抱歉，访问失败");
//			}
//		});
//		listItems.add(new JSONObject());
//		adapter.notifyDataSetChanged();
//		mPullToRefreshView.onRefreshComplete();
	}

	@Override
	public void clearData() {
		pageEnd = false;
		if(urlParam==null)urlParam = new HashMap<String,String>();
		pageIndex = 1;
		urlParam.put("pageNo", String.valueOf(pageIndex));
		adapter.setPageEnd(pageEnd);
		mPullToRefreshView.setMode(Mode.BOTH);
		listItems.clear();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.content_header_left_lay:
			finish();
			break;
		/*case R.id.content_header_right_lay:
			Bundle data = new Bundle();
			data.putString("url", URLs.MAIN_FAXIAN_CONDITION);
			data.putSerializable("condition", (Serializable) conditionMap);
			UIUtil.openActivity(this, ConditionActivity.class, data, 4);
			break;*/
		default:
			break;
		}
	}

}
